import { createStore } from "vuex";
import { setToken, setUserinfo, getUserinfo, getToken, removeToken, removeUserinfo } from "@/utils/cookies";
import { login,userInfo } from "@/api/user"
import { Snackbar } from '@varlet/ui'
export default createStore({
  state: {
    toolbar: JSON.parse(localStorage.getItem("toolbar") || '{"visible": false, "enter": true}'),
    currentUser: getUserinfo() || '{}',
    token: "" || getToken(),
    webInfo: JSON.parse(localStorage.getItem("webInfo") || '{"webName": "ORDINARY", "webTitle": [], "notices": [], "footer": "", "backgroundImage": "", "avatar": "http://47.102.114.131:8080/avatar/avatar.jpg"}')
  },
  getters: {},
  mutations: {
    changeToolbarStatus(state, toolbarState) {
      state.toolbar = toolbarState;
      localStorage.setItem("toolbar", JSON.stringify(toolbarState));
    },
    // loadCurrentUser(state, user) {
    //   state.currentUser = user;
    //   localStorage.setItem("currentUser", JSON.stringify(user));
    // },
    loadWebInfo(state, webInfo) {
      webInfo.webTitle = webInfo.webTitle.split('');
      webInfo.notices = JSON.parse(webInfo.notices);
      state.webInfo = webInfo;
      localStorage.setItem("webInfo", JSON.stringify(webInfo));
    },
    set_user(state, value) { // 设置用户名
      state.currentUser = JSON.stringify(value);
      value && setUserinfo(JSON.stringify(value));
    },
    set_token(state, value) { // 设置token
      state.token = value;
      value && setToken(value);
    },
  },
  actions: {
    // 登录
    loginAction(context, repuestData) {
      return new Promise((resolve, reject) => {
        login(repuestData).then((res) => {
          Snackbar.success(res.message)
          context.commit('set_token', res.token);
          resolve(res);
          userInfo().then((res1) => {
            context.commit('set_user', res1.data);
          }).catch(error => {
     
          })
        }).catch(error => {
     
          reject(error);
        })
      })
    },

    // 登出
    logoutAction({ commit }) {
      return new Promise((resolve, reject) => {
        Logout().then(response => {
          removeToken();
          removeUserinfo();
          // commit('SET_TOKEN', '');
          commit('set_user', '');
          resolve(response);
        })
      })
    },
  },
  modules: {

  },
});
